<?php
namespace app\modules\v1\controllers;
use Yii;
use yii\rest\ActiveController;
use app\modules\v1\models\Kameng;
use app\modules\v1\models\MerchantBillDetails;
use Qiniu\json_decode;
use app\modules\v1\models\Merchant;
use app\modules\v1\models\MerchantWeixin;
use yii\base\Exception;

/**
 * 卡盟进件，进件查询，支付宝，微信下单，下单查询
 * @author lenovo
 *
 */

class KmmerchantorderqueryController extends ActiveController
{
	
    public $modelClass = 'app\modules\v1\models\Kameng';
    
    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['update'], $actions['create'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionIndex()
    {
    	$orders = MerchantBillDetails::find()->where(['status'=>1])->andWhere(['<','km_request_times',3])
    		->orderBy(['id' => SORT_DESC])->all();
    	foreach ($orders as $order){
    		$tr = Yii::$app->db->beginTransaction();
    		try {
    			$orderdetail = MerchantBillDetails::findOne(['id'=>$order->id]);
    			$orderdetail->km_request_times = ($orderdetail->km_request_times)+1;
    			$merchant = Merchant::findOne(['id'=>$order->merchant_id]);
    			if (empty($merchant)){
    				continue;
    			}
    			$map['trxType'] 		= 'OnlineQuery';
    			$map['r1_merchantNo'] 	= $merchant->vnion_merchant_no;
    			$map['r2_orderNumber'] 	= $order->order_id;
    			$map['queryKey'] 		= $merchant->query_key;
    			$res = Kameng::OrderQuery($map);
    			if(!empty($res)){
    				$res = json_decode($res);
    				
    				Yii::info($res, 'merchantorderquery');
    				
    				if(isset($res->retCode) && $res->retCode == '0000'){
    					if($res->r8_orderStatus=='SUCCESS'){
    						$orderdetail->status = 0;
    						$orderdetail->km_status = '支付成功';
    						//推送微信模板消息
    						$weixininfo = MerchantWeixin::findOne(['merchant_id'=>$order->merchant_id]);
    						$paytypes = array(1,2);
    						if(!empty($weixininfo) && in_array($order->pay_type, $paytypes)){
    							if($order->pay_type == '1'){
    								$paytype = '微信支付';
    							}elseif ($order->pay_type == '2'){
    								$paytype = '支付宝支付';
    							}
    							$weixinpush = new Merchant();
    							$weixinpush->WeixinOrderOk($weixininfo->openid,$order->money,$paytype,$order->date_time,$order->order_id);
    						} 
    						//更新用户merchant表中的 account_free_balance账户余额
    						if(($order->money)>0 && ($order->pay_type) == '4' ){
    							$merchant->account_free_balance = ($merchant->account_free_balance)+($order->money);
    							$merchant->update();
    						}
    					}elseif ($res->r8_orderStatus=='INIT'){
    						$orderdetail->km_status = '未支付';
    					}else{
    						$orderdetail->km_status = '等待';
    					}
    				}
    			}
    			$orderdetail->update();
    			$tr->commit();
    		}catch (Exception $e) {
    			$tr->rollBack();
    			continue;
    		}
    	}
    	exit;
    }

}